<template>
  <div id="historyCollectView">
    <input-search />
    <goods-info-cart
      :data="goodsList"
      class="goods-card"
      show-menu
      @select-id="handleClickGoodsInfo"
    />
    <div v-if="goodsList.length === 0">
      <el-empty
        :description="`暂无${
          route.query.type === 'collect' ? '收藏' : '历史'
        }记录，快去查看商品吧！`"
        :image-size="100"
      />
    </div>
  </div>
</template>
<script lang="ts" setup>
import InputSearch from "@/components/InputSearch.vue";
import GoodsInfoCart from "@/components/GoodsInfoCart.vue";
import { useHistoryStore } from "@/store/modules/history";
import { nextTick, ref, watch } from "vue";
import {
  GoodsControllerService,
  GoodsEsDto,
  UserCollectControllerService,
} from "@/api";
import { useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";

const route = useRoute();
const historyStore = useHistoryStore();

function getGoodsList() {
  if (type.value === "collect") {
    GoodsControllerService.getGoodsListByCollectUsingPost().then((res) => {
      goodsList.value = res.data || [];
    });
  } else {
    //获取历史记录
    const historyList = historyStore.getHistoryHistory();
    GoodsControllerService.getGoodsListByIdUsingPost(historyList).then(
      (res) => {
        goodsList.value = res.data || [];
      }
    );
  }
}

const type = ref();

//获取商品数据
const goodsList = ref<GoodsEsDto[]>([]);
watch(
  () => route.query.type,
  () => {
    type.value = route.query.type;
    getGoodsList();
  },
  {
    immediate: true,
  }
);

function handleClickGoodsInfo(id: any) {
  ElMessageBox.confirm("确定要删除这条记录吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 删除收藏数据
      if (type.value === "collect") {
        UserCollectControllerService.delUserCollectUsingDelete([id]).then(
          (res) => {
            getGoodsList();
          }
        );
      } else {
        //删除历史记录
        historyStore.delHistory(id);
        nextTick(() => getGoodsList());
      }
    })
    .catch(() => {});
}
</script>

<style lang="scss" scoped>
#historyCollectView {
  position: absolute;
  width: 80%;

  .goods-card {
    margin-top: 75px;
  }
}
</style>
